class Subject {
  constructor() {
    this.state = 0
    this.observes = []
  }
  getState() {
    return this.state
  }
  //修改state，修改后调用更新所有观察者
  setState(state) {
    this.state = state
    this.notifyAllObservers()
  }
  //触发所有观察者的update方法
  notifyAllObservers() {
    this.observes.forEach((observe) => {
      observe.update()
    })
  }
  //将观察者添加到observes
  attach(observe) {
    this.observes.push(observe)
  }
}

//观察者
class Observe {
  constructor(name, subject) {
    this.name = name
    this.subject = subject
    this.subject.attach(this)
  }
  update() {
    console.log(`${this.name} update： ${this.subject.getState()}`)
  }
}

let s = new Subject()
let o1 = new Observe('o1', s)
let o2 = new Observe('o2', s)

s.setState(1)
s.setState(2)
s.setState(3)
